/***************************************************************
 * Name:      bonusMain.cpp
 * Purpose:   Code for Application Frame
 * Author:    William Wang ()
 * Created:   2009-06-23
 * Copyright: William Wang ()
 * License:
 **************************************************************/

#include "global.h"
#include "bonusMain.h"
#include "lessthan10Pattern.h"
#include "geometryShapeConstruction.h"
#include "menuHandler.h"
#include <wx/msgdlg.h>
#include <wx/panel.h>
#include <wx/memory.h>

//(*InternalHeaders(bonusFrame)
#include <wx/artprov.h>
#include <wx/bitmap.h>
#include <wx/intl.h>
#include <wx/image.h>
#include <wx/string.h>
//*)
#include "toolkit.h"
#include <wx/statbmp.h>
#include <wx/textdlg.h>

#include <wx/grid.h>
#include <wx/event.h>
#include <wx/defs.h> //keycode
#include <wx/tokenzr.h>
#include <wx/display.h>
#include <wx/fileconf.h>
#include <wx/wfstream.h>
#include <wx/filedlg.h>
#include <wx/utils.h>
#include <wx/textctrl.h>
#include <wx/toolbook.h>
#include <wx/button.h>

#include <wx/msw/winundef.h>
#include <wx/xrc/xmlres.h>
//for dynamic class.forName
#include <wx/object.h>
#include <wx/statusbr.h>
#include <wx/log.h>
#include <wx/choicdlg.h>
#include <servprov.h>
#include <wx/webview.h>




using namespace std;

//helper functions
enum wxbuildinfoformat
{
    short_f, long_f };

wxString wxbuildinfo(wxbuildinfoformat format)
{
    wxString wxbuild(wxVERSION_STRING);

    if (format == long_f )
    {
#if defined(__WXMSW__)
        wxbuild << wxT("-Windows");
#elif defined(__UNIX__)
        wxbuild << wxT("-Linux");
#endif

#if wxUSE_UNICODE
        wxbuild << wxT("-Unicode build");
#else
        wxbuild << wxT("-ANSI build");
#endif // wxUSE_UNICODE
    }

    return wxbuild;
}
BEGIN_EVENT_TABLE(bonusFrame,wxFrame)
   EVT_TIMER(ID_TIME_IDFRAME,bonusFrame::OnTimer)
  //  EVT_KEY_DOWN(GlobalEvtHandler::GridArrowEvtHandler)
    EVT_CLOSE(bonusFrame::OnDialogQuit)
END_EVENT_TABLE()


BEGIN_EVENT_TABLE(PopMenuEvtHandler, wxEvtHandler)
    EVT_MENU(ID_RULE_DESC, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_HIDDEN_LOG, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_SAVE_HTML, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_SAVE_FORECAST, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_OPEN_ANALYST, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_FILL_BLANK, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_PRINT_GRID, PopMenuEvtHandler::OnMenuEvent)
    EVT_MENU(ID_OPEN_BLUEBALL, PopMenuEvtHandler::OnMenuEvent)
END_EVENT_TABLE()
     wxGrid*   bonusFrame::Grid1;
    wxString bonusFrame::_WebSite1=wxT("http://www.qiu8.cn/Update/his2010.html");//默认地址一
   // wxString bonusFrame::_WebSite2=wxT("http://www.58cp.com/kaijiangshuju/ssq.txt");
   wxString bonusFrame::_WebSite2=wxT("http://www.17500.cn/getData/ssq.TXT");

    wxString bonusFrame::_Range=wxT("55");

const long bonusFrame::ID_PANEL1 = wxNewId();
//(*IdInit(bonusFrame)
const long bonusFrame::ID_GRID1 = wxNewId();
const long bonusFrame::idMenuQuit = wxNewId();
const long bonusFrame::idMenuAbout = wxNewId();
const long bonusFrame::toolbarAdd = wxNewId();
const long bonusFrame::toolbarsavedb = wxNewId();
const long bonusFrame::toolbarHistoryGrid = wxNewId();
const long bonusFrame::ID_TOOLBAR1 = wxNewId();
//*)
const long bonusFrame::toolbarThread  = wxNewId();;
const long bonusFrame::idMenuConfig  = wxNewId();
const long bonusFrame::idMenuAnalyst = wxNewId();
const long bonusFrame::ID_STATUSBAR1 = wxNewId();

//bonusFrame* bonusFrame::Frame;
       wxBitmap bonusFrame::moneypig;//one
       wxBitmap bonusFrame::money;//one
       wxIcon bonusFrame::appIcon;//
     wxTextCtrl     *bonusFrame::logWin;
     wxLogTextCtrl  *bonusFrame::logger;
     wxLog *bonusFrame::m_logOld;
     wxTextCtrl * bonusFrame::SQLTextBox;
     wxTextCtrl * bonusFrame::LISPCodeBox;
     wxTextCtrl * bonusFrame::LISPCodeName;
     wxTextCtrl * bonusFrame::AIActionWatchTextBox;//观察各种AI分析过程
     wxHtmlWindow * bonusFrame::sqlhtml;
     wxHtmlWindow * bonusFrame::lisphtml;
     wxString bonusFrame::_CLIPBOARD;//剪贴板
     wxStatusBar* bonusFrame::statusbar;

bonusFrame::bonusFrame(wxWindow* parent,wxWindowID id)
{
  BFrame=this;

  this->Grid1=NULL;//clear flag
  this->Panel1=NULL;
  this->saveForecastLight=false;
  this->findBuddyLight=false;

//create status bar

//create Loger
 wxString  TITLE=APP_NAME+
                wxString::FromAscii(DB__YEAR)+
                wxT("-")+
                wxString::FromAscii(DB__MONTH)+
                wxT("-")+
                wxString::FromAscii(DB__DATE)+
                wxT(" Build:")+
                wxString::Format(wxT("%04d"),DB__BUILD);


    //(*Initialize(bonusFrame)
    Create(parent, wxID_ANY, TITLE, wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE|wxWANTS_CHARS, wxT("wxID_ANY"));

    SetMinSize(wxSize(getScreenWidth(),getScreenHeight()));
     Maximize(true);
    MenuBar1 = new wxMenuBar();
    Menu1 = new wxMenu();
    MenuItem1 = new wxMenuItem(Menu1, idMenuQuit, wxT("退出\tAlt-F4"),wxT("退出程序"), wxITEM_NORMAL);
    Menu1->Append(MenuItem1);
    MenuBar1->Append(Menu1, wxT("&F文件"));
 //*)
    //add self menu
     Menutools = new wxMenu();
     Menu_Config_Item_DBConfig = new wxMenuItem(Menu1, idMenuConfig, wxT("数据库目录配置"), wxT("配置数据库文件所在目录"), wxITEM_NORMAL);
     Menu_Config_Item_DBAnalyst = new wxMenuItem(Menu1, idMenuAnalyst, wxT("数据分析"), wxT("数据分析专家根据各种SQL来分析"), wxITEM_NORMAL);
     Menutools->Append(Menu_Config_Item_DBConfig);
     Menutools->Append(Menu_Config_Item_DBAnalyst);

    MenuBar1->Append(Menutools, wxT("&配置"));
//(*Initialize(bonusFrame)
    Menu2 = new wxMenu();
    MenuItem2 = new wxMenuItem(Menu2, idMenuAbout, wxT("关于\tF1"), wxT("Show info about this application"), wxITEM_NORMAL);
    Menu2->Append(MenuItem2);
    MenuBar1->Append(Menu2, wxT("帮助"));
    SetMenuBar(MenuBar1);
    ToolBar1 = new wxToolBar(this, ID_TOOLBAR1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL|wxNO_BORDER, wxT("ID_TOOLBAR1"));

    ToolBar1->SetToolBitmapSize(wxSize(32,32));
    ToolBarItem1 = ToolBar1->AddTool(toolbarAdd, wxT("数据库目录配置"),wxXmlResource::Get()->LoadBitmap(wxT("database")), wxNullBitmap, wxITEM_NORMAL, wxT("寻找数据库所在目录"), wxT("系统配置"));
    ToolBarItem2 = ToolBar1->AddTool(toolbarsavedb, wxT("数据分析及维护功能"), wxXmlResource::Get()->LoadBitmap(wxT("magic")), wxNullBitmap, wxITEM_NORMAL, wxT("数据分析及维护功能"), wxT("数据分析及维护功能"));
    ToolBarItem3 = ToolBar1->AddTool(toolbarHistoryGrid, wxT("历史记录表格趋势分析"),wxXmlResource::Get()->LoadBitmap(wxT("grid")), wxNullBitmap, wxITEM_NORMAL, wxT("历史记录表格趋势分析"), wxT("历史记录表格趋势分析"));
    ToolBarItem4 = ToolBar1->AddTool(ID_RUN_TESTCASE, wxT("运行测试案例"), wxXmlResource::Get()->LoadBitmap(wxT("matrix")), wxNullBitmap, wxITEM_NORMAL, wxT("运行测试案例"), wxT("运行测试案例"));
    ToolBarItemLeft1 = ToolBar1->AddTool(ID_LEFT_TEST1, wxT("运行分析"), wxXmlResource::Get()->LoadBitmap(wxT("tea")), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxT("预留"));
    ToolBarItemLeft2 = ToolBar1->AddTool(ID_LEFT_TEST2, wxT("运行分析"), wxXmlResource::Get()->LoadBitmap(wxT("inernet")), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxT("预留"));
    ToolBarItemLeft3 = ToolBar1->AddTool(ID_LEFT_TEST3, wxT("浏览器"), wxXmlResource::Get()->LoadBitmap(wxT("action")), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxT("浏览器"));
    ToolBarItemLeft4 = ToolBar1->AddTool(ID_LEFT_TEST4, wxT("历史数据统计"), wxXmlResource::Get()->LoadBitmap(wxT("binoculars")), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxT("历史数据统计"));
    ToolBar1->Realize();
    SetToolBar(ToolBar1);
     //CreateStatusBar(3);
     statusbar= new wxStatusBar(this,wxID_ANY);
     statusbar->SetFieldsCount(3);
     statusbar->SetStatusWidths(3,widths);
     SetStatusBar(statusbar);
     statusbar->SetStatusText(wxT("开始时间:")+wxDateTime::Now().FormatTime(), 1);
      m_timer= new wxTimer(this,ID_TIME_IDFRAME);
      m_timer->Start(1000);
//      m_time->Connect(wxTimerEvent,(wxObjectEventFunction)&bonusFrame::OnTimer);
//       Connect(ID_TIME_IDFRAME,,bonusFrame::OnTimer);
 //ADD STATUSBAR
 /*
     StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, wxT("ID_STATUSBAR1"));
    int __wxStatusBarWidths_1[1] = { -1 };
    int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
    StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
    StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
    SetStatusBar(StatusBar1);
    */
    SetStatusText(wxT(""));
    Connect(idMenuQuit,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&bonusFrame::OnQuit);
    Connect(idMenuAbout,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&bonusFrame::OnAbout);
    //*)
    //工具菜单
    Connect(idMenuConfig,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&bonusFrame::configdatabase);
    Connect(idMenuAnalyst,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&bonusFrame::analystExpert);

    //加入grid键盘处理,wxEVT_GRID_SELECT_CELL work,but want only key
    Connect(ID_GRID1,wxEVT_GRID_CELL_LEFT_CLICK,(wxObjectEventFunction)&bonusFrame::OnGrid1CellLeftClick);
    Connect(ID_GRID1,wxEVT_GRID_SELECT_CELL ,wxKeyEventHandler(bonusFrame::OnKeyDown));
    Connect(ID_GRID1,wxEVT_GRID_CELL_RIGHT_CLICK ,wxMouseEventHandler(bonusFrame::OnRightUp));
    Connect(ID_GRID1,wxEVT_GRID_EDITOR_CREATED ,(wxObjectEventFunction)&bonusFrame::OnGrid1CellEditing);


    Connect(toolbarAdd,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::configdatabase);
    Connect(toolbarsavedb,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::analystExpert);
    Connect(toolbarHistoryGrid,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::createGridOfFrame);
//ID_RUN_TESTCASE
      Connect(ID_RUN_TESTCASE,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::runTestCase);
      Connect(ID_LEFT_TEST1,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::experts);
      Connect(ID_LEFT_TEST2,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::experts);
      Connect(ID_LEFT_TEST3,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::openBrowser);
      Connect(ID_LEFT_TEST4,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&bonusFrame::experts);

 // open dialog
   Connect(ID_OPEN_HTMLDLG,wxEVT_COMMAND_HTML_LINK_CLICKED,wxHtmlLinkEventHandler(bonusFrame::OnHtmlLinkClicked));
    //event handler
    //注册菜单处理事件类
    PushEventHandler(new PopMenuEvtHandler(this));

}

bonusFrame::~bonusFrame()
{

    //(*Destroy(bonusFrame)
    //*)
    delete this->Grid1;
    //Grid1=NULL;//clear
    delete this->Panel1;
    //Panel1=NULL;//clear
    BFrame=NULL;//clear
    if(DoubleBallGridCellRenderer::DIRTTABLE!=NULL)
    delete DoubleBallGridCellRenderer::DIRTTABLE;
}

void bonusFrame::OnQuit(wxCommandEvent& event)
{
//    wxMessageBox(wxT(".....Quit"));

//    Close();

    //this->Destroy();
//    exit(0);
}

void bonusFrame::OnAbout(wxCommandEvent& event)
{
    wxBoxSizer *topsizer;
    wxHtmlWindow *html;
    wxDialog dlg(this, wxID_ANY, wxString(wxT("说明")));
    topsizer = new wxBoxSizer(wxVERTICAL);

    html = new wxHtmlWindow(&dlg, wxID_ANY, wxDefaultPosition, wxSize(380, 160), wxSB_HORIZONTAL );//wxHW_SCROLLBAR_NEVER
    html -> SetBorders(0);
    html ->SetPage(appAbout);
    html -> SetSize(html -> GetInternalRepresentation() -> GetWidth(),
                    html -> GetInternalRepresentation() -> GetHeight());
    topsizer -> Add(html, 1, wxALL, 10);
    wxButton *bu1 = new wxButton(&dlg, wxID_OK, wxT("好的"));
    bu1 -> SetDefault();
    topsizer -> Add(bu1, 0, wxALL | wxALIGN_RIGHT, 15);
    dlg.SetSizer(topsizer);
    topsizer -> Fit(&dlg);
    dlg.ShowModal();
    dlg.Destroy();

}
/**
鼠标
*/
void bonusFrame::OnGrid1CellLeftClick(wxGridEvent& ev)
{
    wxGrid* locGrid =wxDynamicCast(ev.GetEventObject(),wxGrid);
//    wxASSERT_MSG(locGrid!=NULL,wxT("it is seem not a grid!"));
    wxString value=locGrid->GetCellValue(ev.GetRow(), ev.GetCol());
    wxLogMessage(wxT("Left click at row %d, col %d,值:%s"), ev.GetRow(), ev.GetCol(),value.c_str());
     ev.Skip();
}
/**
处理数字
*/
void bonusFrame::OnGrid1CellEditing(wxGridEvent& ev)
{
    wxGrid* locGrid =wxDynamicCast(ev.GetEventObject(),wxGrid);
//    wxASSERT_MSG(locGrid!=NULL,wxT("it is seem not a grid!"));
    wxLogMessage(wxT("Left click at row ,iam here"));
     ev.Skip();
}
/*
http://wiki.wxwidgets.org/Catching_key_events_globally
*/
void bonusFrame::OnKeyDown(wxKeyEvent& ev)
{

    switch(ev.GetKeyCode())
    {
        case WXK_F2:
                  toggleLogWindow();
                  break;
        case WXK_F3:
                  complexAI();break;
        case WXK_F4:
                  openBlueBallWindow(false);break;
        case WXK_F5:
                  changeDivideCol();break;
        case WXK_F6:
                    findBuddy();break;
        case WXK_F7:
                  patternFinder();break;
        case WXK_F8:
                  Incantation();break;
        case WXK_F10:
                  patternAI();
   }
    //
    if(ev.GetModifiers()==wxMOD_CONTROL)
      {
       switch(ev.GetKeyCode())
       {

    //保存预测,Ctrl+s
        case 's':
        case 'S':{
           saveForecast();
           break;
                 }
  //调到指定的期 Ctrl+g
        case 'g':
        case 'G':{
           skipTerm();
           break;
                 }
 //打开显示间隔的乒乓 Ctrl+l
         case 'l':
         case 'L':
          {
            if(DoubleBallGridCellRenderer::FILLEDDISTANCE)
            {
             debug(wxT("Grid fill 水平 blank is false"));
             DoubleBallGridCellRenderer::FILLEDDISTANCE=false;
            }else
            {
            debug(wxT("Grid fill 水平 blank set  true"));
            DoubleBallGridCellRenderer::FILLEDDISTANCE=true;
            }
        break;
          }
//打印grid  Ctrl+P
         case 'p':
         case 'P':
          {
    printGrid();
    break;
          }
//粘帖到当前行  Ctrl+w
         case 'W':
         case 'w':
          {
         pasteToGrid(ev);
    break;
          }
//toggle GRID空白  Ctrl+d
       case 'd':
       case 'D':
       {
            if(DoubleBallGridCellRenderer::FILLEDBLANK)
            {
             debug(wxT("Grid fill blank is false"));
             DoubleBallGridCellRenderer::FILLEDBLANK=false;
            }else
            {
            debug(wxT("Grid fill blank set  true"));
            DoubleBallGridCellRenderer::FILLEDBLANK=true;
            }
        break;
       }
//ctrl+r得到最精的统计信息
     case 'r':
     case 'R':
      refreshStastatistics(ev);
     break;
//save to html
      case 'h':
      case 'H':
       saveToHTML();
      break;
       }

      }
     ev.Skip();
   if(Grid1!=NULL)Grid1->ForceRefresh();
}
//清楚空间
bool bonusFrame::clearMainPanel()
{
 if(this->Panel1!=NULL)//toggle
 {

    delete this->Grid1;
    delete this->Panel1;
     this->Grid1=NULL;
     this->Panel1=NULL;//clear
//      wxLogNull* logNo= new wxLogNull();
//     wxLog::SetActiveTarget(NULL);
   //  delete frame->Grid1;
 }
}

/*
保存配置,考虑加入弹出设置窗口
*/
void bonusFrame::configdatabase(wxCommandEvent& event)
{

 // wxDialog* wx=new wxDialog(NULL);
// string result=getUserHome();
//wxMessageBox(wxString(result.c_str(), wxConvUTF8)+wxT("\n  ")+::wxGetCwd());

wxString fileName=getConfigFileDir();
wxString sfilename=wxEmptyString;

if(!wxFile::Exists(fileName))
   {
    wxFile newfile;
    newfile.Create(fileName,true,wxS_DEFAULT);
    newfile.Close();
    sfilename=getDefaultConfigPath()+wxT("\\")+wxString(DoubleBall::_DEFAULTDBNAME,wxConvUTF8);
    }else
    {
     sfilename = wxFileSelector(wxT("选择双色球数据库!"),getDefaultConfigPath(),wxString(DoubleBall::_DEFAULTDBNAME,wxConvUTF8),wxT("db3"),wxT("*.db3"));
    }
//debug(fileName+wxT(" selectd:")+sfilename);
if (sfilename.empty() )//没有选择，直接返回
{
    wxShell(wxT("RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL \"")+fileName+wxT("\""));
    //+fileName

}
//call wxSocketBase::Initialize() once anywhere in your main thread, e.g. in wxApp::OnInit()

wxMessageBox(wxT("保存到配置文件")+fileName);
wxFileInputStream is(fileName);
wxFileConfig *conf = new wxFileConfig(is,wxConvUTF8);
if(!sfilename.empty())
{
  conf->Write(wxT("Global/database"),sfilename);
}
//网络地址，
conf->Write(wxT("Network/website1"),_WebSite1);
conf->Write(wxT("Network/website2"),_WebSite2);
//评估范围
conf->Write(wxT("Global/range"),_Range);

wxFileOutputStream os(fileName);
conf->Save(os);
os.Close();
delete conf;

}


/*
执行一个SQL
*/

void bonusFrame::inputSQL(wxCommandEvent& event)
{

  if(!checkDatabase())return;

wxString input=wxT("");
input= SQLTextBox->GetValue();
 wxString  finalSQL=wxT("");

 wxString sql=wxT("insert into _DBHISTORY(term,date,red1,red2,red3,red4,red5,red6,blue) values");
//wxString input=wxGetTextFromUser(wxT(""),wxT("输入中奖纪录SQL命令"));
wxStringTokenizer lines(input,wxT("\n"));


char* deli="";
if(input.Find(wxT(" "))!=wxNOT_FOUND)
  {
    deli=" ";
  }
if(input.Find(wxT("\t"))!=wxNOT_FOUND )
   {
      deli="\t";
   }
if(input.Find(wxT(","))!=wxNOT_FOUND )
   {
      deli=",";
   }

 int linesMax   =lines.CountTokens();//keep max count
 int linesCount =1;

 while (lines.HasMoreTokens() )
 {
     wxStringTokenizer data(lines.GetNextToken(),wxString::FromAscii(deli));

        if(data.CountTokens()<9)
        {
            wxMessageBox(wxT("不符合格式 term date red1 red2 red3 red4 red5 red6 blue\n 2009001 2009-01-01 01 02 03 04 05 06 16"));
            return;
        }else
        {
            wxString value;
            int i=1;
            int max=data.CountTokens();//keep max count
                while ( data.HasMoreTokens() )
                {
                    value =value.append(wxT("'")+(data.GetNextToken())+wxT("'"));

                    if(i<max)
                    {
                    value=value.append(wxT(","));
                    }
                    i++;
                }
            finalSQL=finalSQL+sql+wxT("(")+value+wxT(")");

        }
    if(linesCount<linesMax)
        {
        finalSQL=finalSQL+ wxT(";\n");
        }

}
//wxMessageBox(input);

size_t lst=finalSQL.find_last_of(wxT(","));
BFrame->SetStatusText(wxString::Format(wxT("last %d,len:%d"),lst,finalSQL.Length()));

if(lst==(finalSQL.Length()-1))finalSQL=finalSQL.substr(0,lst);


 sqlhtml->SetPage(wxT("<html><font color=red>")+finalSQL+wxT("<br>完成!</font></html>"));


if(finalSQL!=wxT(""))
  {
    try
    {

    DoubleBall* db= new DoubleBall();
    db->executeCRUD((wxT("BEGIN TRANSACTION;")+finalSQL+wxT(";commit;")).mb_str());
    delete db;
    }catch(...)
     {
      wxMessageBox(wxT("sql error"));
     }

  }
 // event.Skip();
}

void bonusFrame::createGridOfFrame(wxCommandEvent& ev)
{
 clearMainPanel();
//初始化数据库目录
 if(!checkDatabase())return;
//  wxMessageBox(wxT("配置文件中配置:\n")+wxString(DoubleBall::DB_LOCATION_HOME,wxConvUTF8));
  DoubleBall* db=new DoubleBall();
db->initialize();
  createHistoryGrid(BFrame);
  delete db;
}
//wxString showInputText()
//{
//wxTextCtrl    *m_multitext;
//m_multitext = new wxTextCtrl(NULL,wxID_ANY,wxT("标题"),wxDefaultPosition, wxSize(200,70), wxTE_MULTILINE);
//    m_multitext->SetFont(*wxITALIC_FONT);
//    (*m_multitext) << wxT(" Appended.");
//    m_multitext->SetInsertionPoint(0);
//    m_multitext->WriteText( wxT("Prepended. ") );
//    m_multitext->SetForegroundColour(*wxRED);
//    m_multitext->SetBackgroundColour(*wxLIGHT_GREY);
//
//}

void bonusFrame::analystExpert(wxCommandEvent& event)
{
clearMainPanel();
wxXmlResource::Get()->LoadIcon(wxT("appIco"));

wxPanel *panel = new wxPanel(this,wxID_ANY, wxPoint(0,0),wxSize(300,300),wxTAB_TRAVERSAL|wxWANTS_CHARS);
this->Panel1=panel;

   // create a dummy image list with a few icons
    const wxSize imageSize(32, 32);

    m_imageList = new wxImageList(imageSize.GetWidth(), imageSize.GetHeight());
    m_imageList->
        Add(wxXmlResource::Get()->LoadBitmap(wxT("dig")));
    m_imageList->
        Add(wxXmlResource::Get()->LoadBitmap(wxT("maintain")));
    m_imageList->
        Add(wxXmlResource::Get()->LoadBitmap(wxT("printer")));
//    m_imageList->
//        Add(wxArtProvider::GetIcon(wxART_ERROR, wxART_OTHER, imageSize));
    m_imageList->Add(wxXmlResource::Get()->LoadBitmap(wxT("action")));

    m_bookCtrl= new wxListbook(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL|wxWANTS_CHARS);
    m_bookCtrl->SetImageList(m_imageList);

    wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );

  //create first page
GlobalEvtHandler* books=new GlobalEvtHandler();
//    sqltextctrl->SetHelpText(wxT("输入SQL数据，用空格隔开"));
    m_bookCtrl->AddPage(books->book1MultiThread(m_bookCtrl),wxT("数据分析"),true,0);

//create second page for history record
    m_bookCtrl->AddPage(books->book1InputHistorySQL(m_bookCtrl),wxT("记录维护"),false,1);

//create third page for history record
    m_bookCtrl->AddPage(books->book1LS36(m_bookCtrl),wxT("幻方-洛数"),false,2);
//create database record maintain
    m_bookCtrl->AddPage(books->book1Database(m_bookCtrl),wxT("数据生成"),false,3);

// SetMinSize(getScreenWidth(),getScreenHeight());
    sizer->Add(m_bookCtrl,1,wxEXPAND);

    panel->SetSizer(sizer);
    this->SendSizeEvent();
    //sizer->SetSizeHints(panel);
    sizer->SetMinSize(panel->GetMinSize());
    this->SendSizeEvent();
}


string systemInfo()
{
  wxPuts(wxGetHomeDir());
  wxPuts(wxGetOsDescription());
  wxPuts(wxGetUserName());
  wxPuts(wxGetFullHostName());

  long mem = wxGetFreeMemory().ToLong();

  wxPrintf(wxT("Memory: %ld\n"), mem);
}
//显示Grid右键菜单

    void bonusFrame::OnRightUp(wxMouseEvent& ev)
        {
          ShowContextMenu(::wxGetMousePosition());
        }


void bonusFrame::ShowContextMenu(const wxPoint& pos)
{
    wxPoint gridpoint=Grid1->ScreenToClient(pos);
    wxMenu menu;

    menu.Append(ID_HIDDEN_LOG, wxT("隐藏Log窗口\tF2"));
    menu.Append(ID_RULE_DESC, wxT("显示规则"));
    menu.AppendSeparator();
    menu.Append(ID_SAVE_HTML, wxT("保存为HTML\tCtrl-H"));
    menu.Append(ID_SAVE_FORECAST, wxT("保存预测数据\tCtrl-S"));
    menu.Append(ID_PRINT_GRID, wxT("打印当前窗口\tCtrl-P"));
    menu.Append(ID_FILL_BLANK, wxT("填充间隔数据\tCtrl-D"));
    menu.AppendSeparator();
    menu.Append(ID_OPEN_ANALYST, wxT("打开预测分析窗口\tF3"));
    menu.Append(ID_OPEN_BLUEBALL, wxT("打开篮球窗口"));
//add
menu.AppendSeparator();
wxString curterm=wxEmptyString;
if(BFrame->Grid1!=NULL)
 {
// wxArrayString redballs=getSelectedGridRowRedBall(BFrame->Grid1);
 curterm=getSelectedGridRowTerm(BFrame->Grid1);
 }
menu.Append(wxID_ANY, wxT("当前期")+curterm+wxT("特征\n最大值，最小值"));

//  wxLogMessage(L"mouse right up %d,%d\n转换后%d,%d,row height %d",pos.x,pos.y,gridpoint.x,gridpoint.y,Grid1->GetDefaultRowSize()) ;
    PopupMenu(&menu,gridpoint.x, (gridpoint.y+3*Grid1->GetDefaultRowSize()));
}



void bonusFrame::processMenuEvent(const wxCommandEvent& event)
{
    int id = event.GetId();

    wxString msg = wxString::Format(wxT("Menu ID %d"), id);

     wxMenu* menu =wxDynamicCast(event.GetEventObject(),wxMenu);

    wxMenuItem *item = menu->FindItem(id);
    wxString label(item->GetItemLabelText());

    wxLogMessage(msg+ wxT("  ")+label);
//按下F2
  if(id==ID_HIDDEN_LOG)
   {
   toggleLogWindow();
   }
//CTRL+S,save forcast
  if(id==ID_SAVE_FORECAST)
  {
  saveForecast();
  }
//open blue ball window
  if(id==ID_OPEN_BLUEBALL)
   {
     openBlueBallWindow();
   }
//F3
  if(id==ID_OPEN_ANALYST)
   {
   complexAI();
   }
//ctrl+p
  if(id==ID_PRINT_GRID)
   {
   printGrid();
   }

//ctrl+d
  if(id==ID_FILL_BLANK)
   {
            if(DoubleBallGridCellRenderer::FILLEDBLANK)
            {
             debug(wxT("Grid fill blank is false"));
             DoubleBallGridCellRenderer::FILLEDBLANK=false;
            }else
            {
            debug(wxT("Grid fill blank set  true"));
            DoubleBallGridCellRenderer::FILLEDBLANK=true;
            }
   if(Grid1!=NULL)Grid1->ForceRefresh();
   }

//CTRL+H
 if(id==ID_SAVE_HTML)
   {
    saveToHTML();
   }
}

void bonusFrame::OnHtmlLinkClicked(wxHtmlLinkEvent &event)
{
  if(BFrame->Grid1==NULL)
  {
      wxMessageBox(wxT("Grid没有激活,链接跳转不能执行！"));
      return;
  }
  wxString term=event.GetLinkInfo().GetHref();

   locateByTerm(term);
 event.Skip();
}
/*
复制数据到粘贴板
*/
void bonusFrame::OnCopytoClipBoard(wxCommandEvent& event)
{
  if (wxTheClipboard->Open())
  {
    wxTheClipboard->SetData( new wxTextDataObject(BFrame->_CLIPBOARD));
    wxTheClipboard->Close();
  }
wxMessageBox(wxT("复制完成!"));
}

void bonusFrame::runTestCase(wxCommandEvent& ev)
{

/*
  ::wxStartTimer();
while(!Grid1->IsShownOnScreen())
  {
  if(::wxGetElapsedTime() > 10000) break;//大于10秒strange
  }
*/
wxString content=wxT("选择你需要的分析策略选择\n可以多重选择！！");
wxArrayString names;
switchHashMap forst;
names.Add(wxT("洛书矩阵缩水"));
forst[wxT("洛书矩阵缩水")]=0;

wxMultiChoiceDialog* msg =new wxMultiChoiceDialog(this,content,wxT("选择模拟策略"),names,wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxOK ,wxDefaultPosition);
msg->ShowModal();

wxArrayInt yourchoices=msg->GetSelections();



  //wxMessageBox(wxT("准备分析"));
 //TEST CASE
 //int gridheight=Grid1->GetGridColLabelWindow()->GetSize().GetHeight();
 /*wxSplashScreen* splash = new wxSplashScreen(wxXmlResource::Get()->LoadBitmap(wxT("binoculars")),
          wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
          3000, NULL, -1, wxDefaultPosition, wxDefaultSize,
          wxSIMPLE_BORDER|wxSTAY_ON_TOP);
          */
  wxYield();
BFrame->logWin->Clear();
split->SetSashPosition(32+15);
 this->Panel1->Update();
this->Panel1->UpdateWindowUI(wxUPDATE_UI_NONE);
this->Panel1->Validate();
  for(int i=0;i<yourchoices.Count();i++)
     {
     switch(forst[names[yourchoices[i]]])
        {
         case 0:testCaseLS();break;
         default:wxLogMessage(wxT("test case done."));
        }
     }
}

void bonusFrame::experts(wxCommandEvent& ev)
{
switch(ev.GetId())
  {
   case ID_LEFT_TEST1:wxMessageBox(wxT("1"));break;
   case ID_LEFT_TEST2:wxMessageBox(wxT("2"));break;
   case ID_LEFT_TEST3:wxMessageBox(wxT("3"));break;
   case ID_LEFT_TEST4:findMatchRedBall();break;
  }

}

void bonusFrame::openBrowser(wxCommandEvent& ev)
{

int width=BFrame->GetVirtualSize().GetWidth()-20;
int height=BFrame->GetVirtualSize().GetHeight()-20;
int barHeight=BFrame->GetToolBar()->GetToolSize().GetHeight();
int menuHeigh=BFrame->GetMenuBar()->GetVirtualSize().GetHeight();
long idIEdialog = wxNewId();


wxDialog* dlg =new wxDialog(NULL, idIEdialog,wxT("浏览器"),
                 wxDefaultPosition, wxSize(width, height),wxSYSTEM_MENU | \
             wxMINIMIZE_BOX | \
             wxCLOSE_BOX | \
             wxCAPTION | \
             wxCLIP_CHILDREN);

//dlg->Connect(wxEVT_CLOSE_WINDOW,wxCommandEventHandler(bonusFrame::OnIEDialogQuit));

wxPanel* hpanel=new wxPanel(dlg, BFrame->ID_PANEL1, wxPoint(0,1), wxSize(width,height), wxTAB_TRAVERSAL|wxWANTS_CHARS|wxBORDER_DOUBLE , wxT("search"));
wxWebView* ipIE =  wxWebView::New(hpanel,wxID_ANY,"",wxPoint(1,1),wxSize(width-20,height));
////wxWebView* ipIE =wxWebView::New(this, wxID_ANY, "http://www.wxwidgets.org");
ipIE->LoadURL(wxT("http://www.17500.cn/getData/ssq.TXT"));
dlg->Show();

//ShowModal();

}
void bonusFrame::OnIEDialogQuit(wxCommandEvent& ev)
{

 long key=ev.GetId();

}
void bonusFrame::OnIEHandler(wxCommandEvent& ev)
{
   wxEventType et= ev.GetEventType();
    wxMessageBox(wxT("load ok"));

}


 void bonusFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
 {
  BFrame->statusbar->SetStatusText(wxDateTime::Now().FormatTime(), 2);
 }

void bonusFrame::OnDialogQuit(wxCloseEvent& ev)
{
//    Close();
//    this->Destroy();
//    exit(0);
 Close(true);
    this->Destroy();
}
/**
  * Callback invoked when a loading error occurs
  */
void bonusFrame::OnError(wxWebViewEvent& evt)
{
    wxString errorCategory;
    switch (evt.GetInt())
    {
    case  wxWEB_NAV_ERR_CONNECTION:
        errorCategory = "wxWEB_NAV_ERR_CONNECTION";
        break;

    case wxWEB_NAV_ERR_CERTIFICATE:
        errorCategory = "wxWEB_NAV_ERR_CERTIFICATE";
        break;

    case wxWEB_NAV_ERR_AUTH:
        errorCategory = "wxWEB_NAV_ERR_AUTH";
        break;

    case wxWEB_NAV_ERR_SECURITY:
        errorCategory = "wxWEB_NAV_ERR_SECURITY";
        break;

    case wxWEB_NAV_ERR_NOT_FOUND:
        errorCategory = "wxWEB_NAV_ERR_NOT_FOUND";
        break;

    case wxWEB_NAV_ERR_REQUEST:
        errorCategory = "wxWEB_NAV_ERR_REQUEST";
        break;

    case wxWEB_NAV_ERR_USER_CANCELLED:
        errorCategory = "wxWEB_NAV_ERR_USER_CANCELLED";
        break;

    case wxWEB_NAV_ERR_OTHER:
        errorCategory = "wxWEB_NAV_ERR_OTHER";
        break;
    }

    wxLogMessage("%s", "Error; url='" + evt.GetURL() + "', error='" + errorCategory + "' (" + evt.GetString() + ")");

    //Show the info bar with an error
    wxMessageBox(wxT("An error occurred loading ") + evt.GetURL() + "\n" +
    "'" + errorCategory + "' (" + evt.GetString() + ")");

}
